import requests
import json
import datetime
import base64
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA1

import hashlib
from base64 import b64encode, b64decode
import binascii


class Encrypt:
    def __init__(self, key, iv):
        self.key = key.encode('utf-8')
        self.iv = iv

    # @staticmethod
    def pkcs7padding(self, text):
        """明文使用PKCS7填充 """
        bs = 16
        length = len(text)
        bytes_length = len(text.encode('utf-8'))
        padding_size = length if (bytes_length == length) else bytes_length
        padding = bs - padding_size % bs
        padding_text = chr(padding) * padding
        self.coding = chr(padding)
        return text + padding_text

    def aes_encrypt(self, content):
        """ AES加密 """
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        # 处理明文
        content_padding = self.pkcs7padding(content)
        # 加密
        encrypt_bytes = cipher.encrypt(content_padding.encode('utf-8'))
        # 重新编码
        result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')
        return result

    def aes_decrypt(self, content):
        """AES解密 """
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        content = base64.b64decode(content)
        text = cipher.decrypt(content).decode('utf-8')
        return text.rstrip(self.coding)


# 定义签名函数
def generate_signature(params, private_key_path):

    sorted_params = sorted(params.items(), key=lambda x: x[0])
    sign_str = "&".join([f"{k}={v}" for k, v in sorted_params])
        # 读取私钥文件内容
    with open(private_key_path, 'rb') as f:
        private_key = RSA.import_key(f.read())

    # 生成md5的十六进制表示
    md5_hash = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
    
    # 打印原始字符串和其 MD5 哈希值（十六进制格式）
    print("Original string:", sign_str)
    print("MD5 Hash (hex):", md5_hash)
    
    # 使用SHA1WithRSA的签名方式
    encrypt_hash = SHA1.new(md5_hash.encode('utf-8'))
    # 使用MD5WithRSA的签名方式
    #encrypt_hash = MD5.new(md5_hash.encode('utf-8'))
    signer = pkcs1_15.new(private_key)# 使用私钥进行签名
    signature = signer.sign(encrypt_hash)

    # 打印原始签名（二进制格式）和 Base64 编码后的签名
    print("Signature (binary):", binascii.hexlify(signature).decode('utf-8'))
    signature_b64 = b64encode(signature).decode('utf-8')
    print("Signature (Base64):", signature_b64)
    return signature_b64


def main():
    url = "http://test-astroapi.rong360.com/openapi/gzzj/order/getorderrepayplan"
    aes_private_key = "iBcEa1Lde0768CgY"  # AES加密密钥

    # 指定私钥文件路径
    private_key_file = "app_private_key.pem"
    app_id = "10034"

    biz_content = {
        "out_trade_no": ["SDWX_20241014142421smhk2i"]
    }

    iv = b'\x00' * 16
    a = Encrypt(key=aes_private_key, iv=iv)

    encrypted_biz_content = a.aes_encrypt(json.dumps(biz_content, separators=(',', ':')))

    print("加密后的 biz_content:", encrypted_biz_content)
    decrypted_biz_content = a.aes_decrypt(encrypted_biz_content)
    print('解密后的 biz_content:', decrypted_biz_content)
    # 准备公共请求参数
    # timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    timestamp = "2024-12-05 12:03:10"
    print("当前时间戳:", timestamp)
    print('done')
    header = {
        "Content-Type": "application/json"
    }

    # 组装请求参数
    params = {
        "app_id": app_id,
        "timestamp": timestamp,
        "biz_content": encrypted_biz_content
    }

    # 生成签名
    sign = generate_signature(params, private_key_file)
    params["sign"] = sign

    print("sign:", sign)
    print('done')
    # 发送 POST 请求
    params_json = json.dumps(params, separators=(',', ':'))
    print("请求参数:", params_json)
    response = requests.post(url, data=params_json, headers=header)
    print("响应状态码:", response.status_code)
    print("响应内容:", response.text)
    print("解密内容:", a.aes_decrypt(response.text))


if __name__ == "__main__":
    main()
